import os
import sys
import pandas as pd
import numpy as np
import matplotlib  
matplotlib.use('Agg') 
import matplotlib.pyplot as plt
from matplotlib.pyplot import savefig  
import math
from matplotlib.colors import LogNorm
from scipy import interpolate
import matplotlib.patches as mpatches

def potential_plot(infiles,outfiles=[],params=[]):
	md = pd.read_csv(infiles[0])
	hh = pd.read_csv(infiles[1])
	md_mids = md.mid.unique()
	
	mids	= eval(params[0])
	mnames	= eval(params[1])
	msel	= eval(params[2])
	mn_dict = dict(zip(mids,mnames))
	
	smin,smax = -9.,6.
	rint = 200
	cms =[plt.cm.Blues,plt.cm.Reds,plt.cm.Greens,plt.cm.Purples,plt.cm.Oranges,plt.cm.pink]
	cpch=['blue','red','green','purple','orange','pink']

	cc=np.zeros((len(hh),len(md)),dtype=np.float32)-1
	midict={}
	for (kk,k) in zip(range(len(md)),md_mids):
		midict[kk] = k
		g = md[md.mid==k]
		if len(g)==0: continue
		
		g = g[ g.score > smin ]
		g.score = np.square((g.score-smin)/(smax-smin))
		# md[k][['x','y','score']].to_csv('mall_%s_comp_%d.csv'%(mn_dict[k],rint),index=False)
	
		g = pd.merge(g,hh,on=['x','y'],how='outer')
		g['xys'] = g.x.astype(str)+'_'+g.y.astype(str)
		g.sort_values('xys',inplace=True)
		g.fillna(-1000,inplace=True)
		print g
		cc[:,kk] = g.score
				
	print 'midict',midict
	# np.savetxt('cc.csv',cc)
	
	hh.loc[:,'score'] = np.max(cc,axis=1)
	hh.loc[:,'mid'] = np.argmax(cc,axis=1)
	hh.loc[:,'clr'] = hh.mid
	hh.reset_index(inplace=True)

	if len(msel)>0:
		hh = hh[hh.mid.isin(msel)]
	hh = hh[hh.score>0]
	
	mallpd =  pd.DataFrame({'mid':range(len(midict)),'mall':[mn_dict[midict[x]] for x in range(len(midict))]})
	hh = hh.merge(mallpd,on='mid')
	hh[['x','y','score','mid','mall']].to_csv('mall_comp_%d.csv'%(rint),index=False)
	
	fig = plt.figure(figsize=(8,8),dpi=200)
	ax = fig.add_subplot(111)	
	
	legends=[]
	patches=[]
	
	print hh.mid.unique()
	clrid = 0
	for mid, g in hh.groupby('mid'):
		legends.append(mn_dict[midict[mid]])
		print mnames[mid],len(g)
		g[['x','y']].to_csv('mall_%s_BiggestPotential_grid.csv'%mnames[mid],index=False)
		
		# if not bSize:			
			# ax.scatter(g.x,g.y,s=2,marker='s',c=np.abs((g.s-smin)/(smax-smin)),cmap=cms[mid])
		ax.scatter(g.x,g.y,marker='s',s=hh.score*10,c=cpch[clrid])
			# ax.scatter(g.x,g.y,s=8,c=g.clr)#,edgecolors='w')
		# else:
			# ax.scatter(g.x,g.y,s=g.score,c=g.clr)#,edgecolors='w')
		
		patches.append(	mpatches.Patch(color=cpch[clrid],label=mn_dict[midict[mid]]))
		clrid += 1
		
		
	plt.legend(handles=patches)
	ax.set_xlim((118.5,119))
	ax.set_ylim((31.8,32.3))
	fig.savefig('mall_comp_%d.png'%(rint),dpi=200)		
	plt.close(fig)
